package org.dromara.school.service.impl;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.github.yulichang.toolkit.JoinWrappers;
import com.github.yulichang.wrapper.MPJLambdaWrapper;
import org.dromara.common.core.domain.model.LoginUser;
import org.dromara.common.core.enums.UserType;
import org.dromara.common.core.utils.MapstructUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.mybatis.core.page.TableDataInfo;
import org.dromara.common.mybatis.core.page.PageQuery;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import lombok.RequiredArgsConstructor;
import org.dromara.common.satoken.utils.LoginHelper;
import org.dromara.school.domain.*;
import org.dromara.school.domain.vo.ClassesVo;
import org.dromara.school.service.*;
import org.dromara.system.domain.SysUser;
import org.dromara.system.domain.vo.SysUserVo;
import org.dromara.system.service.ISysUserService;
import org.springframework.stereotype.Service;
import org.dromara.school.domain.bo.StudentBo;
import org.dromara.school.domain.vo.StudentVo;
import org.dromara.school.mapper.StudentMapper;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.Collection;
import java.util.stream.Collectors;

/**
 * 学生管理Service业务层处理
 *
 * @author gjb
 * @date 2025-05-28
 */
@RequiredArgsConstructor
@Service
public class StudentServiceImpl implements IStudentService {

    private final StudentMapper baseMapper;

    private final IStudentParentService studentParentService;

    private final IClassesService classesService;

    private final IBindingSchoolsService bindingSchoolsService;

    private final ISysUserService sysUserService;

    private final ITeacherClassesService teacherClassesService;





    /**
     * 查询学生管理
     */
    @Override
    public StudentVo queryById(Long studentId){
        return baseMapper.selectVoById(studentId);
    }

    /**
     * 查询学生管理列表
     */
    @Override
    public TableDataInfo<StudentVo> queryPageList(StudentBo bo, PageQuery pageQuery) {

        MPJLambdaWrapper<Student> mpj = JoinWrappers.lambda(Student.class)
            .selectAll(Student.class)
            .selectAs(Classes::getClassYear, StudentBo::getClassYear)
            .selectAs(Classes::getClassNum, StudentBo::getClassNum)
            .leftJoin(Classes.class, Classes::getId, Student::getClassesId)
            .selectAs(Campus::getCampusName, StudentBo::getCampusName)
            .logicDelToOn()
            .orderByAsc(Classes::getClassNum)
            .leftJoin(Campus.class, Campus::getCampusId, Classes::getSchoolCampusId).orderByDesc(Classes::getClassYear);
        if (bo.getSchoolCampusId() != null) {
            mpj.eq(Student::getSchoolCampusId, bo.getSchoolCampusId());
        }

        if (bo.getClassYear() != null) {
            mpj.eq(Classes::getClassYear, bo.getClassYear());
        }

        if (bo.getClassesId() != null) {
            mpj.eq(Student::getClassesId, bo.getClassesId());
        }


        if (bo.getStudentName() != null) {
            mpj.like(Student::getStudentName, bo.getStudentName());
        }
        if (bo.getStudentStatus() != null) {
            mpj.eq(Student::getStudentStatus, bo.getStudentStatus());
        }
        if (bo.getNation() != null) {
            mpj.eq(Student::getNation, bo.getNation());
        }


        LoginUser loginUser = LoginHelper.getLoginUser();
        UserType userType = UserType.getUserType(loginUser.getUserType());


        switch (userType) {
            case SYS_USER:

                break;
            case SCHOOLADMIN:
                //如果用户类型是SCHOOLADMIN 那么学校管理员能查看自己所在校区的所班级学校
                //1.根据用户id 拿到教师id
//                SysUserVo sysUserVo = this.sysUserService.selectUserById(loginUser.getUserId());
//                Long teacherId = sysUserVo.getTeacherId();
                //2.根据教师id 拿到校区id
                List<BindingSchools> bindingSchools = this.bindingSchoolsService.findByTeacherId(loginUser.getTeacherId());
                List<Long> campusids = bindingSchools.stream()
                    .map(BindingSchools::getSchoolCampusId)
                    .collect(Collectors.toList());
                mpj.in(Student::getSchoolCampusId,campusids);

//                List<Integer> campusids = Arrays.asList(loginUser.getSysUser().getSchoolCampusIds().split(",")).stream().map(i -> Integer.valueOf(i)).collect(Collectors.toList());
//                mpj.in(Student::getSchoolCampusId,campusids);
                break;
            case TEACHER:
                List<Object> t1 = this.teacherClassesService.findbyTeacherId(loginUser.getUserId());
                List<Object> t2 = this.classesService.findbyTeacherId(loginUser.getTeacherId());
                t1.addAll(t2);

                if (t1.size() > 0) {
                    mpj.selectAll(Classes.class)
                        .in(Classes::getId, t1);
                }else {
                    mpj.selectAll(Classes.class)
                        .in(Classes::getId, 0);
                }


                break;
            default:
                return null;
        }

        IPage<StudentVo> ipage = baseMapper.selectJoinPage(
            new Page<StudentVo>(pageQuery.getPageNum(), pageQuery.getPageSize()),
            StudentVo.class, mpj
        );


        changeYearToName(ipage.getRecords());
        //数据列表
//        List<ClassesVo> items = ipage.getRecords();
//        //记录总数
//        long total = ipage.getTotal();

        TableDataInfo<StudentVo> classesResult = TableDataInfo.build(ipage);


        return classesResult;

    }

    private void changeYearToName(List<StudentVo> list) {
        list.stream().map(
            item -> {

                if (item.getClassYear() != null && item.getClassYear() != 0L && item.getClassNum() != null && item.getSchoolCampusId() != null) {
                    getClassName(item);
                }
                return item;
            }

        ).collect(Collectors.toList());
    }

    private void getClassName(StudentVo item) {
        if(item!=null){
            Map<Integer, String> map = classesService.getSchoolGrades(item.getSchoolCampusId());
            Map<Integer, String> schoolClasses = map.entrySet().stream()
                .collect(Collectors.toMap(entry -> Integer.parseInt(String.valueOf(entry.getKey())), Map.Entry::getValue));
            item.setClassName(schoolClasses.get(item.getClassYear().intValue()) + item.getClassNum() + "班");
        }

    }

    /**
     * 查询学生管理列表
     */
    @Override
    public List<StudentVo> queryList(StudentBo bo) {
        LambdaQueryWrapper<Student> lqw = buildQueryWrapper(bo);
        return baseMapper.selectVoList(lqw);
    }

    private LambdaQueryWrapper<Student> buildQueryWrapper(StudentBo bo) {
        Map<String, Object> params = bo.getParams();
        LambdaQueryWrapper<Student> lqw = Wrappers.lambdaQuery();
        lqw.like(StringUtils.isNotBlank(bo.getStudentName()), Student::getStudentName, bo.getStudentName());
        lqw.eq(bo.getStudentNumber() != null, Student::getStudentNumber, bo.getStudentNumber());
        lqw.eq(bo.getStudentCode() != null, Student::getStudentCode, bo.getStudentCode());
        lqw.eq(bo.getSex() != null, Student::getSex, bo.getSex());
        lqw.eq(StringUtils.isNotBlank(bo.getHeadSculptureId()), Student::getHeadSculptureId, bo.getHeadSculptureId());
        lqw.eq(StringUtils.isNotBlank(bo.getStudentStatus()), Student::getStudentStatus, bo.getStudentStatus());
        lqw.eq(StringUtils.isNotBlank(bo.getNation()), Student::getNation, bo.getNation());
        lqw.eq(StringUtils.isNotBlank(bo.getAddress()), Student::getAddress, bo.getAddress());
        lqw.eq(StringUtils.isNotBlank(bo.getProvince()), Student::getProvince, bo.getProvince());
        lqw.eq(StringUtils.isNotBlank(bo.getCity()), Student::getCity, bo.getCity());
        lqw.eq(StringUtils.isNotBlank(bo.getDistricts()), Student::getDistricts, bo.getDistricts());
        lqw.eq(bo.getClassesId() != null, Student::getClassesId, bo.getClassesId());
        lqw.eq(bo.getSchoolCampusId() != null, Student::getSchoolCampusId, bo.getSchoolCampusId());
        lqw.eq(StringUtils.isNotBlank(bo.getContact()), Student::getContact, bo.getContact());
        lqw.eq(StringUtils.isNotBlank(bo.getStudentAccount()), Student::getStudentAccount, bo.getStudentAccount());
        return lqw;
    }

    /**
     * 新增学生管理
     */
    @Override
    public Boolean insertByBo(StudentBo bo) {
        Student add = MapstructUtils.convert(bo, Student.class);
        validEntityBeforeSave(add);
        boolean flag = baseMapper.insert(add) > 0;
        if (flag) {
            bo.setStudentId(add.getStudentId());
        }
        return flag;
    }

    /**
     * 修改学生管理
     */
    @Override
    public Boolean updateByBo(StudentBo bo) {
        Student update = MapstructUtils.convert(bo, Student.class);
        validEntityBeforeSave(update);
        return baseMapper.updateById(update) > 0;
    }

    /**
     * 保存前的数据校验
     */
    private void validEntityBeforeSave(Student entity){
        //TODO 做一些数据校验,如唯一约束
    }

    /**
     * 批量删除学生管理
     */
    @Override
    public Boolean deleteWithValidByIds(Collection<Long> ids, Boolean isValid) {
        if(isValid){
            //TODO 做一些业务上的校验,判断是否需要校验
        }
        return baseMapper.deleteBatchIds(ids) > 0;
    }

    @Override
    public StudentVo selectStudentParentsById(Long id) {
        StudentVo studentVo = new StudentVo();
        List<StudentParent> parents = this.studentParentService.findStudentParentByStudentId(id);
        studentVo.setStudentParents(parents);
        return studentVo;
    }

    @Override
    public Student findStudent(StudentVo studentVo) {
        if (studentVo != null) {
            LambdaQueryWrapper<Student> queryWrapper = new LambdaQueryWrapper<>();
            if (studentVo.getStudentCode() != null) {
                queryWrapper.eq(Student::getStudentCode, studentVo.getStudentCode());
            }
            return this.baseMapper.selectOne(queryWrapper);

        }
        return null;
    }

    @Override
    public int editStudentParent(StudentBo studentBo) {
        try {
            //获取学生id
            Long studentId = studentBo.getStudentId();
            //清理原先数据
            this.studentParentService.deleteByStudentId(studentId);
            Long schoolCampusId = studentBo.getSchoolCampusId();
            //获取家长信息集合
            List<StudentParent> studentParents = studentBo.getStudentParents();
            //遍历处理家长数据
            studentParents.stream().forEach(item -> {
                StudentParent studentParent = new StudentParent();
                studentParent.setStudentId(studentId);
                studentParent.setSchoolCampusId(schoolCampusId);
                studentParent.setParentName(item.getParentName());
                studentParent.setPosition(item.getPosition());
                studentParent.setRelationShip(item.getRelationShip());
                studentParent.setTelphone(item.getTelphone());
               this.studentParentService.save(studentParent);
            });
        } catch (Exception e) {
            e.printStackTrace();
        }


        return 1;

    }
}
